package org.ihelpuoo.xml;

import java.util.Iterator;

import org.w3c.dom.Document;
import org.w3c.dom.Node;

/**
 * <b>XMLWalker class:</b>
 * <hr color=grey size=1>
 *
 *	Deep first!
 *
 * @author zozoh  created @ 2007
 *
 */
public class XMLWalker implements Iterator<Node>
{

	private Node	root;
	private Node	cur;
	private Node	next;

	public XMLWalker(Node node)
	{
		root = node;
		cur = null;
		next = (node instanceof Document ? node.getFirstChild() : node);
	}

	public boolean hasNext()
	{
		if (next == null)
			return false;
		return true;
	}

	private Node getNext(Node node)
	{
		Node n = node.getFirstChild();
		if (null == n)
			n = node.getNextSibling();
		if (null == n)
			return jump(node);
		return n;
	}

	private Node jump(Node node)
	{
		if (node == root)
			return null;
		Node p = node.getParentNode();
		while (p.getNextSibling() == null && p != root)
			p = p.getParentNode();
		if (p == root)
			return null;
		return p.getNextSibling();
	}

	public Node next()
	{
		if (null == next)
			return null;
		cur = next;
		next = getNext(cur);
		return cur;
	}

	public void remove()
	{
		Node old = cur;
		next();
		old.getParentNode().removeChild(old);
	}

}
